$(function() {
    initBuildingTree();
    equipmentValidtor();
    initAssetTypeTree();
    getDeviceByPage(1);
});

$("#q_assetTypeName").on("click",function(){
    showMenu3();
});

function showMenu3() {
    var deptIdObj = $("#q_assetTypeName");
    var deptIdOffset = $("#q_assetTypeName").offset();
    $("#buildingModal3").css({left:deptIdOffset.left + "px", top:deptIdOffset.top + deptIdObj.outerHeight() + "px"}).slideDown("fast");
    $("body").bind("mousedown", onBodyDown3);
}

function onBodyDown3(event) {
    if (!(event.target.id == "q_assetTypeName" || event.target.id == "buildingModal3" || $(event.target).parents("#buildingModal3").length>0)) {
        hideMenu3();
    }
}

function hideMenu3() {
    $("#buildingModal3").fadeOut("fast");
    $("body").unbind("mousedown", onBodyDown3);
}

//请求所有建筑结构数据
function initBuildingTree(){
	$("#treeOrg").html(loader);
    // PostForm("/cwp/front/sh/region!execute", "uid=region004x", "", successResultBuilding, '',"frmTree");

    $.getJSON('/cwp/src/json/system/asset/region_004x.json',function(data){
        successResultBuilding(data);
    })
}

function initAssetTypeTree(){
    // PostForm("/cwp/front/sh/assetType!execute", "uid=asset004x", "", successResultAssetType, '',"frmTree");

    $.getJSON('/cwp/src/json/system/asset/asset_type_004x.json',function(data){
        successResultAssetType(data);
    })
}

function successResultBuilding(result){
    switch (result.returnCode) {
        case "0":
            if(result.beans.length>0) {
                constructTree(result.beans);
            }
            break;
        case "1":
            tipModal("icon-cross", "空间资产树获取失败");
            break;
        case "-9999":
            tipModal("icon-cross", "空间资产树获取失败");
            break;
        default:
            break;
    }
}

function successResultAssetType(result){
    switch (result.returnCode) {
        case "0":
            if(result.beans.length>0) {
                constructTree2(result.beans);
            }
            break;
        case "1":
            tipModal("icon-cross", "资产类型树获取失败");
            break;
        case "-9999":
            tipModal("icon-cross", "资产类型树获取失败");
            break;
        default:
            break;
    }
}

//重构树对象数据
function constructTree(data){
    var zNodes=[];
    //数据排序
    for(var i=0; i<data.length; i++){
        var obj = new Object();
        obj.id=data[i].regionId;
        obj.pId=data[i].parentId;
        obj.name=data[i].regionName
        if(i==0) {
            obj.open=true;
        }
        zNodes.push(obj);
    }
    var setting = {
        view: {
            showIcon: false,
            selectedMulti: false
        },
        data: {
            simpleData: {
                enable: true
            }
        },
        callback: {
            beforeClick:beforeClick
        }
    };
    $.fn.zTree.init($("#treeOrg"), setting, zNodes);
    // var zTree = $.fn.zTree.getZTreeObj("treeOrg");
    getDeptTreeModal(zNodes);
}

//重构树对象数据
function constructTree2(data){
	 var zNodes=[];
	    //数据排序
	    for(var i=0; i<data.length; i++){
	        var obj = new Object();
	        obj.id=data[i].assetTypeId;
	        obj.pId=data[i].parentId;
	        if(data[i].funName != null && data[i].funName!=''){
	        	obj.name=data[i].funName;
	        }
	        else if(data[i].typeName != null && data[i].typeName!=''){
	        	obj.name=data[i].typeName;
	        }
	        else if(data[i].sysName != null && data[i].sysName!=''){
	        	obj.name=data[i].sysName;
	        }
	        else if(data[i].parkName != null && data[i].parkName!=''){
	        	obj.name=data[i].parkName;
	        }
	        if(i==0) {
	            obj.open=true;
            }
	        zNodes.push(obj);
	    }
	    
	    var setting = {
	            view: {
	                showIcon: false,
	                selectedMulti: false
	            },
	            data: {
	                simpleData: {
	                    enable: true
	                }
	            },
	            callback: {
	                beforeClick:beforeClick2
	            }
	        };
	        $.fn.zTree.init($("#treeOrgModal3"), setting, zNodes);
	        getDeptTreeModal2(zNodes);
}
//点击节点事件
function beforeClick(treeId, treeNode){
    var regionId=treeNode.id;
    $("#regionId").val(regionId);
    isFirst=true;
    getDeviceByPage(1);
}

//点击节点事件
function beforeClick2(treeId, treeNode){
    var assertTypeId=treeNode.id;
    var assertTypeName=treeNode.name;
    $("#q_assetTypeName").val(assertTypeName);
    $("#q_assetTypeId").val(assertTypeId);
}


//搜索设备列表
$("#btnSearch").on("click",function(){
    isFirst=true;
    getDeviceByPage(1);
});

//请求设备列表数据
function getDeviceByPage(pageIndex)
{
    $.getJSON('/cwp/src/json/system/asset/asset_list_d001.json',function(data){
        var loaderDeviceTab = new LoaderTableNew("deviceTable","/cwp/front/sh/asset!execute","uid=d001x",pageIndex,10,deviceListResultArrived,"",paginationCallback,"frmSearch");
        // loaderDeviceTab.Display();
        deviceListResultArrived(data);
        loaderDeviceTab.loadSuccessed(data);
    })

}

//渲染设备列表
function deviceListResultArrived(result)
{
    if(result.returnCode=="0"){
        var outHtml = template("dataTmpl", result);
        $("#deviceTable tbody").html(outHtml);
    }
}

//当前页，加载容器
function paginationCallback(page_index){
    if(!isFirst) {
        getDeviceByPage(page_index+1);
    }
}
//初始化文件上传控件
$(function() {
    $("#file_upload").uploadify({
        height        : 28,
        swf           : '../../../assets/lib/uploadify/uploadify.swf?ver='+Math.random(),
        uploader      : '/cwp/front/sh/asset!execute?uid=m007_2x',
        width         : 78,
        'fileTypeExts': '*.xls; *.xlsx', //文件后缀限制 默认：'*.*'
        'fileSizeLimit': '10240KB', //文件大小限制 0为无限制 默认KB
        'fileTypeDesc' : '.xls; *.xlsx文件格式',//文件类型描述
        'method': 'post', //提交方式Post 或Get 默认为Post
        'buttonText': '', //按钮文字

        'multi': false, //多文件上传
        'fileObjName': 'files[]', //设置一个名字，在服务器处理程序中根据该名字来取上传文件的数据。默认为Filedata
        'queueID': 'I am dont need',  //默认队列ID
        'removeCompleted': true, //上传成功后的文件，是否在队列中自动删除
        'overrideEvents': ['onDialogClose', 'onSelectError','onUploadStart', 'onUploadSuccess', 'onUploadError'],//重写事件
        //返回一个错误，选择文件的时候触发          
        'onSelectError': function (file, errorCode, errorMsg) {
            var msgText = "";
            switch (errorCode) {
                case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
                    //this.queueData.errorMsg = "每次最多上传 " + this.settings.queueSizeLimit + "个文件";
                    msgText += "每次最多上传 " + this.settings.queueSizeLimit + "个文件";
                    break;
                case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
                    msgText += "文件大小超过限制" + this.settings.fileSizeLimit + "";
                    break;
                case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
                    msgText += "文件大小为0";
                    break;
                case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
                    msgText += "文件格式不正确，仅限 " + this.settings.fileTypeExts;
                    break;
                default:
                    msgText += "错误代码：" + errorCode + "\n" + errorMsg;
            }
            tipModal('icon-cross',msgText);
        },
        // 文件开始上传时回调函数
        'onUploadStart': function (file) {
            //显示上传状态
            $("#uploadTip").text("正在上传...").attr("class","t-loading-cmcc");
        },

        //检测FLASH失败调用
        'onFallback': function () {
            tipModal("icon-cross", "您未安装FLASH控件，无法上传图片！请安装FLASH控件后再试。");
        },

        //文件上传成功后的回掉方法
        'onUploadSuccess': function (file, data, response) {
            var data=JSON.parse(data)
            if(data.returnCode == '0'){
                //excel列表数据
                getDeviceByPage(1);
                tipModal('icon-checkmark','导入完成');
            }
            else if(data.returnCode == '-9999'){
                tipModal('icon-cross','导入失败');
            }
            else{
                tipModal('icon-cross',data.returnMessage);
            }
            $("#uploadTip").text("批量导入").attr("class","t-btn t-btn-blue");
        },

        //文件上传出错时触发，参数由服务端程序返回。
        'onUploadError': function (file, errorCode, errorMsg, errorString) {
            tipModal('icon-cross',"上传出现异常，请重新上传");
        }
    });
});